package com.springboot.demo.thread_pool;

import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier测试
 *
 * @author supu
 * @date 2019-03-28 17:43
 **/
public class CyclicBarrierDemo {
    private final Map<String,Integer> countMap = new ConcurrentHashMap<>(1);

    private final CyclicBarrier barrier = new CyclicBarrier(5,() -> System.out.println(countMap.get("test")));

    public static void main(String[] args) {
        CyclicBarrierDemo demo = new CyclicBarrierDemo();
        demo.runTest();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("cyclicBarrier 重来***********************");

        demo.runTest();
    }

    private void runTest(){
        for(int i=0; i< 5; i++){
            new Thread(() -> {
                try {
//                    System.out.println(Thread.currentThread().getName() + "is run");
//                    Thread.sleep(10);
//                    System.out.println(Thread.currentThread().getName() + "is end");
                    synchronized (countMap) {
                        countMap.put("test", countMap.get("test") == null ? 1 : (countMap.get("test") + 1));
                        System.out.println(Thread.currentThread().getName() + " count:" + countMap.get("test"));
                    }
                    barrier.await();

                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
